#include <my_head.h>

int main(int argc, const char *argv[]){
    if(3 != argc){
        printf("Usage : %s <IP> <PORT>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sockfd)
        ERR_LOG("socket error");
    
    // 填充 服务器! 网络信息结构体
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t serveraddr_len = sizeof(serveraddr);
    // 收发数据
    char buff[128] = {0};
    while(1){
        fgets(buff, sizeof(buff), stdin);
        buff[strlen(buff)-1] = '\0';
        // 给服务器发送数据
        if(-1 == sendto(sockfd, buff, sizeof(buff), 0, (struct sockaddr *)&serveraddr, serveraddr_len)){
            ERR_LOG("sendto error");
        }
        // 接收服务器回复的消息
        memset(buff, 0, sizeof(buff)); // 清空buff
        // 这里就无需再保存服务器的网络信息结构体了 因为我们serveraddr 填充后没被修改过
        if(-1 == recvfrom(sockfd, buff, sizeof(buff), 0, NULL, NULL)){
            ERR_LOG("recvfrom error");
        }
        // 将收到的消息打印到终端
        printf("服务器回复:[%s]\n", buff);
    }
    // 关闭套接字
    close(sockfd);

    return 0;
}